package com.lfs.softwork.service;

import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
@AllArgsConstructor
@Slf4j
public class FileService {
    private static final int MAX_LINES = 3000;
    private static final int HALF_MAX_LINES = MAX_LINES / 2;
    private static final String WORK_DIR = "软著";

    /**
     * 处理文本
     * @param file 文本文件
     * @param dir 保存目录
     */
    public void textFile(MultipartFile file,String dir){
        try {
            // 读取文件内容
            BufferedReader reader = new BufferedReader(new InputStreamReader(file.getInputStream()));
            List<String> lines = reader.lines()
                    .map(this::processLine)
                    .filter(line -> !line.isEmpty())
                    .collect(Collectors.toList());
            // 去除连续的换行
            String fileName = file.getName();
            List<String> processedLines = lines.stream()
                    .filter(line -> !line.isEmpty())
//                    .filter(line->{
//                        if (fileName.contains("java")) {
//                            return !line.startsWith("//") && !line.startsWith("/*") && !line.startsWith("*") && !line.startsWith("*/");
//                        }else if (fileName.contains("python")){
//                            return !line.startsWith("#") && !line.startsWith("'''") && !line.startsWith("\"\"\"");
//                        }else {
//                            return true;
//                        }
//                    })
                    .collect(Collectors.toList());
            reader.close();
            // 根据处理后的行数判断是否需要截取
            if (processedLines.size() > MAX_LINES) {
                List<String> truncatedLines = new ArrayList<>();
                truncatedLines.addAll(processedLines.subList(0, HALF_MAX_LINES));
                truncatedLines.addAll(processedLines.subList(processedLines.size() - HALF_MAX_LINES, processedLines.size()));
                processedLines = truncatedLines;
            }
            // 获取下载目录路径
            Path downloadDir = getDownloadDirectory();
            Path softworkDir = downloadDir.resolve(WORK_DIR);
            if (StringUtils.isNotEmpty(dir)) softworkDir = softworkDir.resolve(dir);
            // 如果不存在则创建
            Files.createDirectories(softworkDir);
            // 生成新的文件名
//            String newFileName = generateFileName();
            String newFileName = "源代码.txt";
            Path newFilePath = softworkDir.resolve(newFileName);
            // 将处理后的内容写入新文件
            Files.write(newFilePath, processedLines);

        } catch (IOException e) {
            log.error("文件读取失败");
            e.printStackTrace();
        }
    }
    private String processLine(String line) {
        // 去除每行开头的空格
        line = line.replaceAll("^\\s+", "");
        // 去除所有连续空格
        line = line.replaceAll("\\s+", " ");
        return line;
    }
//    private String generateFileName() {
//        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd-HH-mm-ss");
//        LocalDateTime now = LocalDateTime.now();
//        return "已处理代码_" + dtf.format(now) + ".txt";
//    }
    private Path getDownloadDirectory() {
        String os = System.getProperty("os.name").toLowerCase();
        Path downloadDir;
        if (os.contains("win")) {
            downloadDir = Paths.get(System.getProperty("user.home"), "Downloads");
        } else if (os.contains("mac")) {
            downloadDir = Paths.get(System.getProperty("user.home"), "Downloads");
        } else {
            // Linux 或其他 Unix-like 系统
            downloadDir = Paths.get(System.getProperty("user.home"), "Downloads");
        }
        return downloadDir;
    }
}
